﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.QPZS.EPC.API.Domain.Entities;

namespace Wicture.QPZS.EPC.API.Throttlings
{
    public class ThrottingProxy : IThrottingProxy
    {
        private readonly IThrottling[] _throttlings;

        public ThrottingProxy(IThrottling[] throttlings)
        {
            _throttlings = throttlings;
        }

        public void Throtting(ThrottlingContext invokeContext)
        {
            var throttlings = SelectThrottlings(invokeContext);
            if (!(throttlings?.Any() ?? false))
            {
                return;
            }
            foreach (var throttling in throttlings)
            {
                throttling.Invoke(invokeContext);
            }
        }

        private IEnumerable<IThrottling> SelectThrottlings(ThrottlingContext invokeContext)
        {
            return _throttlings.Where(s => s.ServicePackageTypes.Contains(invokeContext.ServicePackage.PackageType)).OrderBy(s => s.Order);
        }
    }
}
